from dpdata import LabeledSystem,MultiSystems,System
import os
from subprocess import Popen,PIPE

path = "./"

outcar_path = []
for root, dirs, files in os.walk(path, topdown=False):
    for name in files:
        if "OUTCAR" == name:
            outcar_path.append((root, name))

ms=MultiSystems()
for path_to_outcar,outcar in outcar_path:
    try:
        p2 = Popen('if [ $(grep NELMIN {0} | wc -l) -eq 2 ];then sed -i "0,/NELMIN/s/NELMIN/TMP/" {0};fi' .format(os.path.join(path_to_outcar,outcar)) ,shell=True,stdout=PIPE)
        p2.wait()   

        ls=LabeledSystem(os.path.join(path_to_outcar,outcar))
        POSCAR = System(os.path.join(path_to_outcar,'POSCAR'))
        ls.data['atom_names']=POSCAR.data['atom_names']
    except:
        print(path_to_outcar,"has errors.")
    if len(ls)>0:
        ms.append(ls)

ms.to_deepmd_npy('deepmd',set_size=ms.get_nframes())
